package main

import (
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"log"

	"github.com/minio/minio-go/v7/pkg/credentials"
)

func createBucket(mc *minio.Client, bucketName string) (err error) {
	err = mc.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{Region: "us-east-1", ObjectLocking: false}) // Region : 存储桶（us-east-1：默认）
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Successfully created mybucket.")
	return
}
func listBucket(mc *minio.Client) (err error) {
	buckets, err := mc.ListBuckets(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, bucket := range buckets {
		fmt.Printf("bucket名称：%s，创建时间：%s\n", bucket.Name, bucket.CreationDate)
	}
	return
}
func bucketExits(mc *minio.Client, bucketName string) (err error) {
	found, err := mc.BucketExists(context.Background(), bucketName)
	if err != nil {
		fmt.Println(err)
		return
	}
	if found {
		fmt.Println("Bucket found")
	} else {
		fmt.Println("Bucket not found")
	}
	return
}
func deleteBucket(mc *minio.Client, bucketName string) (err error) {
	err = mc.RemoveBucket(context.Background(), bucketName)
	if err != nil {
		fmt.Println(err)
		return
	}
	return
}
func listObjs(mc *minio.Client, bucketName string) (err error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	objectCh := mc.ListObjects(ctx, bucketName, minio.ListObjectsOptions{
		Prefix:    "制图", // 前缀条件
		Recursive: true, // 循环
	})
	for object := range objectCh {
		if object.Err != nil {
			fmt.Println(object.Err)
			return
		}
		fmt.Printf("文件名：%s，大小：%verb", object.Key, object.Size)
	}
	return
}
func uploadObject(mc *minio.Client, bucketName, objectName string, filePath string, contentType string) {
	n, err := mc.FPutObject(context.Background(),
		bucketName, // bucket
		objectName, // 上传文件名称
		filePath,   // 上传文件地址
		minio.PutObjectOptions{ContentType: contentType}) // 上传文件类型
	if err != nil {
		log.Fatalln(err)
	}

	log.Printf("Successfully uploaded 文件名 =  %s  ，大小 = %d byte ，  md5 = %s  \n", objectName, n.Size, n.ETag)
}

func main() {
	endpoint := "minio.dongzi.online"
	accessKeyID := "dongdonghe"   // ID
	secretAccessKey := "19981014" // Secret
	useSSL := false               // ssl配置

	// Initialize minio client object.
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		log.Fatalln(err)
	}
	// log.Printf("%#v\n", minioClient) // minioClient is now setup

	// 创建bucket
	// createBucket(minioClient, "dong")

	// 列出bucket
	// listBucket(minioClient)

	// 检查bucket是否存在
	// bucketExits(minioClient, "dong1")

	// 删除bucket
	// deleteBucket(minioClient, "dong")

	// 获取所有文件对象
	// listObjs(minioClient, "dong")

	//上传文件
	uploadObject(minioClient, "tmp", "test.txt", "./go.mod", "text/plain")

}
